import Vue from "vue";
import Vuex from "vuex";

import SecureLS from "secure-ls";
import CreatePersistedstate from "vuex-persistedstate";

import { menu, user } from "./modules";

const LS = new SecureLS({ isCompression: false });

Vue.use(Vuex);

const modules = {
	menu,
	user
};

const actions = {
	// 重置所有模块数据
	resetState({ dispatch }) {
		const root = true;
		Object.keys(modules).forEach(moduleName => {
			dispatch(`${moduleName}/clearState`, null, { root });
		});
	}
};

// 是否加密数据
const hasEncry = import.meta.env.APP_ENCRY === "true";
const storage = hasEncry
	? {
			getItem: k => LS.get(k),
			removeItem: k => LS.remove(k),
			setItem: (k, v) => LS.set(k, v)
		}
	: localStorage;

const statePlugin = CreatePersistedstate({
	key: "rsb_v2",
	paths: ["menu", "user"],
	reducer: state => ({
		menu: state?.menu,
		user: state?.user
	}),
	storage
});

const store = new Vuex.Store({
	actions,
	modules,
	plugins: [statePlugin]
});

export default store;
